//
//  BKSystemMessageMannager.m
//  bestkeep
//
//  Created by windCould on 17/1/6.
//  Copyright © 2017年 utouu. All rights reserved.
//

#import "BKSystemMessageMannager.h"
#import "BKUserStatusInfo.h"
#import "BKUserUnitRequestAPI.h"
#import "Mediator+BKMy.h"
#import "BKUserLoginController.h"
#import "RootNavigationController.h"
#import "BKIntegralViewController.h"
NSString * const  NSNotificationPushToSystemMessageController = @"NSNotificationPushToSystemMessageController";
//NSString * const NSNotificationHaveNewNewMessage = @"NSNotificationHaveNewNewMessage";

@interface BKSystemMessageMannager ()

@property(nonatomic,strong)UIWindow * rootWindow;

@end


@implementation BKSystemMessageMannager


-(instancetype)initConfig
{
    self = [super init];
    if (self) {
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(haveMessageToPush) name:NSNotificationPushToSystemMessageController object:nil];
    }
    return self;
}

+(BKSystemMessageMannager *)mananger
{
    static BKSystemMessageMannager * instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        instance = [[BKSystemMessageMannager alloc]initConfig];
        
    });
    
    return instance;
}

-(void)haveMessageToPush
{
   UINavigationController * navc = [self getCurrentViewControllerWithWindow:self.rootWindow];
   UIViewController * systemVC = [[Mediator sharedInstance] BKSystemMessageVC];
   [navc pushViewController:systemVC animated:YES];
 
}

-(BOOL)getMessageStatusWithApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  
    NSDictionary *userInfo= launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        //点击远程通知启动的程序
        
    }else{
        //直接点击App图标启动的程序
        if ([UIApplication sharedApplication].applicationIconBadgeNumber>0) {
           
            [self setMessageNoread];
        }
        
     }
 
    if (launchOptions[@"userInfo"]) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           
            NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
            [center postNotificationName:NSNotificationPushToSystemMessageController object:nil];
            
        });
    }
    //角标清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    return YES;
}


-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    // 程序正处在前台运行，直接返回
    if (application.applicationState == UIApplicationStateActive) return;
    
    if ([self getCurrentViewControllerWithWindow:self.rootWindow]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
            if (![userInfo isLogin]) {
                
                BKUserLoginController *loginVC = [[BKUserLoginController alloc] init];
                 RootNavigationController* navc = [[RootNavigationController alloc] initWithRootViewController:loginVC];
                [[self getCurrentViewControllerWithWindow:self.rootWindow] presentViewController:navc animated:YES completion:nil];
                
            }else{
                BKIntegralViewController *sign = [[BKIntegralViewController alloc]init];
                [[self getCurrentViewControllerWithWindow:self.rootWindow].navigationController pushViewController:sign animated:YES];
            }
        });
    }

}
-(void)getMessgaeWhthApplicationDidBecomeActive:(UIApplication *)application {
    
    
    long messgaeNum = [UIApplication sharedApplication].applicationIconBadgeNumber;
    NSLog(@"%ld",messgaeNum);
    //直接点击App图标启动的程序
    if ([UIApplication sharedApplication].applicationIconBadgeNumber > 0) {
       
        
         [self  setMessageNoread];
        
    } else {
        
        
    }

    [self getUnreadMessageNum];
    
}

-(void)getMessageWhenApplicationWillEnterForeground:(UIApplication *)application {
    
    long messgaeNum = [UIApplication sharedApplication].applicationIconBadgeNumber;
    NSLog(@"%ld",messgaeNum);
    //直接点击App图标启动的程序
    if ([UIApplication sharedApplication].applicationIconBadgeNumber>0) {
       
        [self  setMessageNoread];
    }
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

-(void)getMessageNumWhenApplication:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo window:(UIWindow *)window{
  
   
    self.rootWindow = window;
    [[NSNotificationCenter defaultCenter]postNotificationName:@"NSNotificationHaveNewNewMessage" object:nil];
    [self setMessageNoread];
    
    if (application.applicationState == UIApplicationStateActive) {
     
        [self  setMessageNoread];
      
     } else if(application.applicationState == UIApplicationStateInactive){
        
     //   [[HomeViewController instance] setSelectedIndex:3];
        NSLog(@"aaaaaaaaaaaaaaa%@",userInfo);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
            [center postNotificationName:NSNotificationPushToSystemMessageController object:nil];
        });
        
    } else {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    
            NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
            [center postNotificationName:NSNotificationPushToSystemMessageController object:nil];
        });
    }
    
}


-(void)setMessageNoread{
    
    BKUserStatusInfo * statusInfo = [BKUserStatusInfo currentUser];
    [statusInfo.realm beginWriteTransaction];
    
    statusInfo.unreadMessageNum = @"noread";
    
    [statusInfo.realm commitWriteTransaction];
}

-(void)getUnreadMessageNum
{
    BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
    if (userInfo.isLogin) {
        
        [BKUserUnitRequestAPI getUnreadMessageNumberWithUserid:nil resultBlock:^(id obj, NSError *error) {
            
            if (obj) {
                
                NSDictionary * dataDict = obj;
                if ([dataDict objectForKey:@"success"]) {
                    
                    NSDictionary * dict = dataDict[@"data"];
                    NSString * uNreadNum = [NSString stringWithFormat:@"%@",dict[@"unreadCount"]];
                    if ([uNreadNum intValue] > 0) {
                        
                    } else {
                        
                        uNreadNum = @"";
                    }
                    BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
                    [userInfo.realm  beginWriteTransaction];
                    
                    userInfo.unreadMessageNum = uNreadNum;
                    
                    [userInfo.realm commitWriteTransaction];
                }
                
            } else {
                
                NSLog(@"未读消息数网络请求失败");
            }
            
        }];
        
    }
}


//获取当前控制器

- (UINavigationController *) getCurrentViewControllerWithWindow:(UIWindow *)window
{
    UINavigationController *navigationController;
    
    UITabBarController *tabBarController = (UITabBarController *)window.rootViewController;
    
    if (tabBarController.selectedIndex == 0) {
        
        navigationController = window.rootViewController.childViewControllers.firstObject;
        
    }else if (tabBarController.selectedIndex == 1) {
        
        navigationController = window.rootViewController.childViewControllers[1];
        
    }else if (tabBarController.selectedIndex == 3) {
        
        navigationController = window.rootViewController.childViewControllers[3];
        
    }else {
        
        navigationController = window.rootViewController.childViewControllers.firstObject;
    }
    
    return navigationController;
    
}

@end
